package com.example.myshopping3.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.myshopping3.mapper.CarMapper;
import com.example.myshopping3.model.Car;
import com.example.myshopping3.model.view.CarView;
import com.example.myshopping3.service.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CarServiceImpl extends ServiceImpl<CarMapper, Car> implements CarService {
    @Resource
    private CarMapper carMapper;

    /**
     * 添加购物车方法
     * @param car
     * 实现思路，检测购物车中是否存在当前商品
     *  如果存在则更新数量
     *  如果不存在则新增商品
     */
    @Override
    public void addCar(Car car) {
        //根据用户编号和商品编号查询购物车中是否存在该商品
        QueryWrapper<Car> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",car.getUserId()).eq("book_id",car.getBookId());
        Car car1 = this.getOne(wrapper);
        //判断是否存在，如果存在则更新数量
        if(car1 != null){
            //更新数量
            UpdateWrapper<Car> updateWrapper = new UpdateWrapper<>();
            updateWrapper
                    .set("car_count",car1.getCarCount()+car.getCarCount())
                    .eq("user_id",car.getUserId())
                    .eq("book_id",car.getBookId());
            this.update(updateWrapper);
        }else{
            //新增
            this.save(car);
        }
    }

    @Override
    public List<CarView> getCarInfo(int userId) {
        return carMapper.getCarInfo(userId);
    }
}
